package cn.demoncat.util.quartz;

import cn.demoncat.util.lang.IDUtil;
import cn.demoncat.util.lang.ReflectMethodUtil;
import cn.demoncat.util.quartz.constant.JobMsg;
import cn.demoncat.util.web.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 本地任务处理器
 *
 * @author 延晓磊
 *
 * @since 2018年8月10日
 */
@ConditionalOnMissingBean(JobExecutor.class)
@Component("jobExecutor")
public class LocalJobExecutor implements JobExecutor{

    @Resource
    private SpringUtil springUtil;

    private static final Logger LOG = LoggerFactory.getLogger(LocalJobExecutor.class);

    /**
     * 执行任务/[记录日志、添加监控]/通知远程系统执行
     *
     * @param groupId
     * @param jobId
     * @param handler   任务执行器Bean，实现execute(param)方法
     * @param param     任务执行参数
     *
     */
    @Override
    public void execute(String groupId, Long jobId, String handler, String param) {
        // 触发成功
        String jobLogId = IDUtil.getSnowflakeId();
        LOG.info(JobMsg.TRIGGER_INIT_SUCCESS, groupId, jobId, jobLogId);
        // 获取Handler
        Object bean = null;
        try {
            bean = springUtil.getBean(handler);
        } catch (Exception e) {
            LOG.error(JobMsg.HANDLER_NOT_FOUND, handler, e);
        }
        if (bean == null) {
            LOG.error(JobMsg.HANDLER_NOT_FOUND, handler);
        }else {
            // 执行任务
            try {
                ReflectMethodUtil.invoke(bean, "execute", param);
                LOG.info(JobMsg.RUN_SUCCESS, jobLogId);
            } catch (Exception e) {
                LOG.error(JobMsg.RUN_FAIL, jobLogId, e);
            }
        }
    }
}
